/**
 * hook_core.c - 钩子框架核心实现（类eBPF架构）
 * 
 * 这个文件提供钩子框架的核心功能，包括：
 * - 钩子点注册机制
 * - 动态函数拦截
 * - 回调处理机制
 * - 上下文管理
 * 
 * 框架只提供基础设施，不包含具体的拦截逻辑
 */

#define _GNU_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dlfcn.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/types.h>
#include <stdarg.h>
#include <time.h>
#include <sys/time.h>
#include <errno.h>
#include <assert.h>

#include "../../include/hook_framework.h"

/* ===== 全局变量 ===== */

/* 日志级别 (默认设置为WARN，减少日志输出) */
int g_log_level = LOG_WARN;

/* 自定义钩子点存储 */
typedef struct hook_entry {
    char name[64];                      /* 钩子点名称 */
    int type;                           /* 钩子类型 */
    int group;                          /* 所属组 */
    void* original_func;                /* 原始函数指针 */
    int enabled;                        /* 是否启用 */
    hook_callback_node_t* pre_callbacks;  /* 前置回调链表 */
    hook_callback_node_t* post_callbacks; /* 后置回调链表 */
    pthread_mutex_t mutex;              /* 互斥锁 */
    struct hook_entry* next;            /* 链表指针 */
} hook_entry_t;

/* 钩子点链表头 */
static hook_entry_t* g_hook_entries = NULL;

/* 组启用状态 */
static int g_group_enabled[HOOK_GROUP_MAX] = {1, 1, 1, 1, 1, 1, 1};

/* 框架互斥锁 */
static pthread_mutex_t g_framework_mutex = PTHREAD_MUTEX_INITIALIZER;

/* 上下文ID计数器 */
static uint64_t g_context_counter = 0;

/* 初始化标志 */
static int g_initialized = 0;

/* 加载的插件 */
static void* g_plugins[64] = {0};
static int g_plugin_count = 0;

/* ===== 内部辅助函数 ===== */

/**
 * 获取时间戳（毫秒）
 */
static int64_t get_timestamp_ms(void) {
    struct timeval tv;
    gettimeofday(&tv, NULL);
    return (int64_t)tv.tv_sec * 1000 + tv.tv_usec / 1000;
}

/**
 * 获取时间戳字符串
 */
void get_timestamp_str(char* buffer, size_t size) {
    struct timeval tv;
    struct tm* tm_info;
    
    gettimeofday(&tv, NULL);
    tm_info = localtime(&tv.tv_sec);
    
    snprintf(buffer, size, "%04d-%02d-%02d %02d:%02d:%02d.%03ld",
             tm_info->tm_year + 1900, tm_info->tm_mon + 1, tm_info->tm_mday,
             tm_info->tm_hour, tm_info->tm_min, tm_info->tm_sec, 
             tv.tv_usec / 1000);
}

/**
 * 创建新的钩子点
 */
static hook_entry_t* create_hook_entry(const char* name, int type, int group, void* original_func) {
    hook_entry_t* entry = calloc(1, sizeof(hook_entry_t));
    if (!entry) return NULL;
    
    strncpy(entry->name, name, sizeof(entry->name) - 1);
    entry->type = type;
    entry->group = group;
    entry->original_func = original_func;
    entry->enabled = 1;
    entry->pre_callbacks = NULL;
    entry->post_callbacks = NULL;
    pthread_mutex_init(&entry->mutex, NULL);
    entry->next = NULL;
    
    return entry;
}

/**
 * 查找钩子点
 */
static hook_entry_t* find_hook_entry(const char* name) {
    hook_entry_t* current = g_hook_entries;
    
    while (current) {
        if (strcmp(current->name, name) == 0) {
            return current;
        }
        current = current->next;
    }
    
    return NULL;
}

/**
 * 添加回调节点到链表
 */
static int add_callback_node(hook_callback_node_t** head, hook_callback_t callback, 
                            void* user_data, uint32_t priority) {
    hook_callback_node_t* new_node = calloc(1, sizeof(hook_callback_node_t));
    if (!new_node) return 0;
    
    new_node->callback = callback;
    new_node->user_data = user_data;
    new_node->priority = priority;
    new_node->next = NULL;
    
    // 如果链表为空或新节点优先级更高
    if (*head == NULL || (*head)->priority > priority) {
        new_node->next = *head;
        *head = new_node;
        return 1;
    }
    
    // 插入到正确位置
    hook_callback_node_t* current = *head;
    while (current->next && current->next->priority <= priority) {
        current = current->next;
    }
    
    new_node->next = current->next;
    current->next = new_node;
    return 1;
}

/**
 * 移除回调节点
 */
static int remove_callback_node(hook_callback_node_t** head, hook_callback_t callback) {
    if (!*head) return 0;
    
    // 如果是头节点
    if ((*head)->callback == callback) {
        hook_callback_node_t* to_remove = *head;
        *head = (*head)->next;
        free(to_remove);
        return 1;
    }
    
    // 查找并移除
    hook_callback_node_t* current = *head;
    while (current->next) {
        if (current->next->callback == callback) {
            hook_callback_node_t* to_remove = current->next;
            current->next = current->next->next;
            free(to_remove);
            return 1;
        }
        current = current->next;
    }
    
    return 0;
}

/**
 * 清理回调链表
 */
static void clean_callback_list(hook_callback_node_t** head) {
    hook_callback_node_t* current = *head;
    hook_callback_node_t* next;
    
    while (current) {
        next = current->next;
        free(current);
        current = next;
    }
    
    *head = NULL;
}

/* ===== 对外API实现 ===== */

/**
 * 初始化钩子框架
 */
int init_hook_framework(void) {
    pthread_mutex_lock(&g_framework_mutex);
    
    if (g_initialized) {
        pthread_mutex_unlock(&g_framework_mutex);
        return 1;
    }
    
    // 初始化默认值
    g_log_level = LOG_INFO;
    g_hook_entries = NULL;
    g_context_counter = 0;
    
    // 设置所有组为启用状态
    for (int i = 0; i < HOOK_GROUP_MAX; i++) {
        g_group_enabled[i] = 1;
    }
    
    // 从环境变量加载配置
    const char* log_level_str = getenv("HOOK_LOG_LEVEL");
    if (log_level_str) {
        if (strcasecmp(log_level_str, "ERROR") == 0) g_log_level = LOG_ERROR;
        else if (strcasecmp(log_level_str, "WARN") == 0) g_log_level = LOG_WARN;
        else if (strcasecmp(log_level_str, "INFO") == 0) g_log_level = LOG_INFO;
        else if (strcasecmp(log_level_str, "DEBUG") == 0) g_log_level = LOG_DEBUG;
    }
    
    const char* groups_str = getenv("HOOK_ENABLED_GROUPS");
    if (groups_str) {
        // 先禁用所有组
        for (int i = 0; i < HOOK_GROUP_MAX; i++) {
            g_group_enabled[i] = 0;
        }
        
        // 然后启用指定的组
        char* groups_copy = strdup(groups_str);
        char* token = strtok(groups_copy, ",");
        while (token) {
            if (strcasecmp(token, "file_io") == 0) g_group_enabled[HOOK_GROUP_FILE_IO] = 1;
            else if (strcasecmp(token, "network") == 0) g_group_enabled[HOOK_GROUP_NETWORK] = 1;
            else if (strcasecmp(token, "process") == 0) g_group_enabled[HOOK_GROUP_PROCESS] = 1;
            else if (strcasecmp(token, "memory") == 0) g_group_enabled[HOOK_GROUP_MEMORY] = 1;
            else if (strcasecmp(token, "crypto") == 0) g_group_enabled[HOOK_GROUP_CRYPTO] = 1;
            else if (strcasecmp(token, "system") == 0) g_group_enabled[HOOK_GROUP_SYSTEM] = 1;
            else if (strcasecmp(token, "custom") == 0) g_group_enabled[HOOK_GROUP_CUSTOM] = 1;
            token = strtok(NULL, ",");
        }
        free(groups_copy);
    }
    
    g_initialized = 1;
    log_message(LOG_INFO, "钩子框架已初始化，版本: %s", HOOK_FRAMEWORK_VERSION);
    
    pthread_mutex_unlock(&g_framework_mutex);
    return 1;
}

/**
 * 清理钩子框架
 */
void cleanup_hook_framework(void) {
    pthread_mutex_lock(&g_framework_mutex);
    
    if (!g_initialized) {
        pthread_mutex_unlock(&g_framework_mutex);
        return;
    }
    
    // 清理所有钩子点
    hook_entry_t* current = g_hook_entries;
    hook_entry_t* next;
    
    while (current) {
        next = current->next;
        
        // 清理回调链表
        clean_callback_list(&current->pre_callbacks);
        clean_callback_list(&current->post_callbacks);
        
        // 销毁互斥锁
        pthread_mutex_destroy(&current->mutex);
        
        // 释放节点
        free(current);
        current = next;
    }
    
    g_hook_entries = NULL;
    
    // 卸载插件
    for (int i = 0; i < g_plugin_count; i++) {
        if (g_plugins[i]) {
            // 调用清理函数
            plugin_cleanup_t cleanup_func = dlsym(g_plugins[i], "plugin_cleanup");
            if (cleanup_func) {
                cleanup_func();
            }
            
            dlclose(g_plugins[i]);
            g_plugins[i] = NULL;
        }
    }
    g_plugin_count = 0;
    
    g_initialized = 0;
    log_message(LOG_INFO, "钩子框架已清理");
    
    pthread_mutex_unlock(&g_framework_mutex);
}

/**
 * 注册钩子点
 */
int register_hook_point(const char* name, int type, int group, void* original_func) {
    if (!name || group < 0 || group >= HOOK_GROUP_MAX) {
        log_message(LOG_ERROR, "注册钩子点失败: 无效参数 (name=%s, group=%d)", 
                   name ? name : "(NULL)", group);
        return 0;
    }
    
    pthread_mutex_lock(&g_framework_mutex);
    
    // 如果钩子点已存在，返回成功
    hook_entry_t* existing = find_hook_entry(name);
    if (existing) {
        pthread_mutex_unlock(&g_framework_mutex);
        return 1;
    }
    
    // 创建新钩子点
    hook_entry_t* new_entry = create_hook_entry(name, type, group, original_func);
    if (!new_entry) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_ERROR, "注册钩子点失败: 内存分配错误");
        return 0;
    }
    
    // 添加到链表头
    new_entry->next = g_hook_entries;
    g_hook_entries = new_entry;
    
    log_message(LOG_INFO, "已注册钩子点: %s (类型=%d, 组=%d)", name, type, group);
    
    pthread_mutex_unlock(&g_framework_mutex);
    return 1;
}

/**
 * 注销钩子点
 */
int unregister_hook_point(const char* name) {
    if (!name) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    
    // 如果是链表头
    if (g_hook_entries && strcmp(g_hook_entries->name, name) == 0) {
        hook_entry_t* to_remove = g_hook_entries;
        g_hook_entries = g_hook_entries->next;
        
        // 清理回调链表
        clean_callback_list(&to_remove->pre_callbacks);
        clean_callback_list(&to_remove->post_callbacks);
        
        // 销毁互斥锁
        pthread_mutex_destroy(&to_remove->mutex);
        
        // 释放节点
        free(to_remove);
        
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_INFO, "已注销钩子点: %s", name);
        return 1;
    }
    
    // 在链表中查找
    hook_entry_t* current = g_hook_entries;
    while (current && current->next) {
        if (strcmp(current->next->name, name) == 0) {
            hook_entry_t* to_remove = current->next;
            current->next = current->next->next;
            
            // 清理回调链表
            clean_callback_list(&to_remove->pre_callbacks);
            clean_callback_list(&to_remove->post_callbacks);
            
            // 销毁互斥锁
            pthread_mutex_destroy(&to_remove->mutex);
            
            // 释放节点
            free(to_remove);
            
            pthread_mutex_unlock(&g_framework_mutex);
            log_message(LOG_INFO, "已注销钩子点: %s", name);
            return 1;
        }
        current = current->next;
    }
    
    pthread_mutex_unlock(&g_framework_mutex);
    log_message(LOG_WARN, "注销钩子点失败: 未找到 %s", name);
    return 0;
}

/**
 * 查找钩子点
 */
hook_point_t* find_hook_point(const char* name) {
    if (!name) return NULL;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(name);
    pthread_mutex_unlock(&g_framework_mutex);
    
    return (hook_point_t*)entry;
}

/**
 * 启用钩子点
 */
int enable_hook_point(const char* name) {
    if (!name) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(name);
    
    if (entry) {
        entry->enabled = 1;
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_INFO, "已启用钩子点: %s", name);
        return 1;
    }
    
    pthread_mutex_unlock(&g_framework_mutex);
    log_message(LOG_WARN, "启用钩子点失败: 未找到 %s", name);
    return 0;
}

/**
 * 禁用钩子点
 */
int disable_hook_point(const char* name) {
    if (!name) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(name);
    
    if (entry) {
        entry->enabled = 0;
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_INFO, "已禁用钩子点: %s", name);
        return 1;
    }
    
    pthread_mutex_unlock(&g_framework_mutex);
    log_message(LOG_WARN, "禁用钩子点失败: 未找到 %s", name);
    return 0;
}

/**
 * 启用钩子组
 */
int enable_hook_group(int group) {
    if (group < 0 || group >= HOOK_GROUP_MAX) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    g_group_enabled[group] = 1;
    pthread_mutex_unlock(&g_framework_mutex);
    
    log_message(LOG_INFO, "已启用钩子组: %s", get_hook_group_name(group));
    return 1;
}

/**
 * 禁用钩子组
 */
int disable_hook_group(int group) {
    if (group < 0 || group >= HOOK_GROUP_MAX) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    g_group_enabled[group] = 0;
    pthread_mutex_unlock(&g_framework_mutex);
    
    log_message(LOG_INFO, "已禁用钩子组: %s", get_hook_group_name(group));
    return 1;
}

/**
 * 检查钩子点是否启用
 */
int is_hook_point_enabled(const char* name) {
    if (!name) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(name);
    
    if (entry) {
        int point_enabled = entry->enabled;
        int group_enabled = g_group_enabled[entry->group];
        pthread_mutex_unlock(&g_framework_mutex);
        return point_enabled && group_enabled;
    }
    
    pthread_mutex_unlock(&g_framework_mutex);
    return 0;
}

/**
 * 检查钩子组是否启用
 */
int is_hook_group_enabled(int group) {
    if (group < 0 || group >= HOOK_GROUP_MAX) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    int enabled = g_group_enabled[group];
    pthread_mutex_unlock(&g_framework_mutex);
    
    return enabled;
}

/**
 * 获取钩子组名称
 */
const char* get_hook_group_name(int group) {
    static const char* group_names[] = {
        "file_io",
        "network",
        "process",
        "memory",
        "crypto",
        "system",
        "custom"
    };
    
    if (group >= 0 && group < HOOK_GROUP_MAX) {
        return group_names[group];
    }
    
    return "unknown";
}

/**
 * 注册前置回调函数
 */
int register_pre_callback(const char* hook_name, hook_callback_t callback, void* user_data, uint32_t priority) {
    if (!hook_name || !callback) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(hook_name);
    
    if (!entry) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_WARN, "注册前置回调失败: 未找到钩子点 %s", hook_name);
        return 0;
    }
    
    pthread_mutex_lock(&entry->mutex);
    int result = add_callback_node(&entry->pre_callbacks, callback, user_data, priority);
    pthread_mutex_unlock(&entry->mutex);
    
    pthread_mutex_unlock(&g_framework_mutex);
    
    if (result) {
        log_message(LOG_INFO, "已注册前置回调: %s (优先级=%u)", hook_name, priority);
    } else {
        log_message(LOG_ERROR, "注册前置回调失败: 内存分配错误");
    }
    
    return result;
}

/**
 * 注册后置回调函数
 */
int register_post_callback(const char* hook_name, hook_callback_t callback, void* user_data, uint32_t priority) {
    if (!hook_name || !callback) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(hook_name);
    
    if (!entry) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_WARN, "注册后置回调失败: 未找到钩子点 %s", hook_name);
        return 0;
    }
    
    pthread_mutex_lock(&entry->mutex);
    int result = add_callback_node(&entry->post_callbacks, callback, user_data, priority);
    pthread_mutex_unlock(&entry->mutex);
    
    pthread_mutex_unlock(&g_framework_mutex);
    
    if (result) {
        log_message(LOG_INFO, "已注册后置回调: %s (优先级=%u)", hook_name, priority);
    } else {
        log_message(LOG_ERROR, "注册后置回调失败: 内存分配错误");
    }
    
    return result;
}

/**
 * 移除前置回调函数
 */
int remove_pre_callback(const char* hook_name, hook_callback_t callback) {
    if (!hook_name || !callback) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(hook_name);
    
    if (!entry) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_WARN, "移除前置回调失败: 未找到钩子点 %s", hook_name);
        return 0;
    }
    
    pthread_mutex_lock(&entry->mutex);
    int result = remove_callback_node(&entry->pre_callbacks, callback);
    pthread_mutex_unlock(&entry->mutex);
    
    pthread_mutex_unlock(&g_framework_mutex);
    
    if (result) {
        log_message(LOG_INFO, "已移除前置回调: %s", hook_name);
    } else {
        log_message(LOG_WARN, "移除前置回调失败: 未找到回调函数");
    }
    
    return result;
}

/**
 * 移除后置回调函数
 */
int remove_post_callback(const char* hook_name, hook_callback_t callback) {
    if (!hook_name || !callback) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(hook_name);
    
    if (!entry) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_WARN, "移除后置回调失败: 未找到钩子点 %s", hook_name);
        return 0;
    }
    
    pthread_mutex_lock(&entry->mutex);
    int result = remove_callback_node(&entry->post_callbacks, callback);
    pthread_mutex_unlock(&entry->mutex);
    
    pthread_mutex_unlock(&g_framework_mutex);
    
    if (result) {
        log_message(LOG_INFO, "已移除后置回调: %s", hook_name);
    } else {
        log_message(LOG_WARN, "移除后置回调失败: 未找到回调函数");
    }
    
    return result;
}

/**
 * 创建上下文
 */
hook_context_t* create_context(const char* name) {
    if (!name) return NULL;
    
    hook_context_t* context = calloc(1, sizeof(hook_context_t));
    if (!context) {
        log_message(LOG_ERROR, "创建上下文失败: 内存分配错误");
        return NULL;
    }
    
    pthread_mutex_lock(&g_framework_mutex);
    hook_entry_t* entry = find_hook_entry(name);
    
    if (entry) {
        context->id = __sync_fetch_and_add(&g_context_counter, 1);
        context->type = entry->type;
        context->group = entry->group;
        context->name = strdup(name);
        context->flags = CTX_FLAG_ACTIVE;
        context->original_func = entry->original_func;
        context->start_time = get_timestamp_ms();
        context->thread_id = get_thread_id();
        context->process_id = get_process_id();
    } else {
        free(context);
        context = NULL;
    }
    
    pthread_mutex_unlock(&g_framework_mutex);
    
    if (!context) {
        log_message(LOG_WARN, "创建上下文失败: 未找到钩子点 %s", name);
    }
    
    return context;
}

/**
 * 销毁上下文
 */
void destroy_context(hook_context_t* context) {
    if (!context) return;
    
    // 释放名称字符串
    if (context->name) {
        free((void*)context->name);
    }
    
    free(context);
}

/**
 * 执行所有前置回调
 */
int execute_pre_callbacks(hook_point_t* point, hook_context_t* context) {
    if (!point || !context) return 1; // 默认允许继续
    
    hook_entry_t* entry = (hook_entry_t*)point;
    hook_callback_node_t* current;
    int continue_execution = 1;
    
    pthread_mutex_lock(&entry->mutex);
    current = entry->pre_callbacks;
    
    while (current && continue_execution) {
        // 调用回调函数
        continue_execution = current->callback(context, current->user_data);
        
        if (!continue_execution) {
            set_context_flag(context, CTX_FLAG_BLOCKED);
            log_message(LOG_DEBUG, "钩子点 %s 被前置回调拦截", entry->name);
        }
        
        current = current->next;
    }
    
    pthread_mutex_unlock(&entry->mutex);
    return continue_execution;
}

/**
 * 执行所有后置回调
 */
void execute_post_callbacks(hook_point_t* point, hook_context_t* context) {
    if (!point || !context) return;
    
    hook_entry_t* entry = (hook_entry_t*)point;
    hook_callback_node_t* current;
    
    pthread_mutex_lock(&entry->mutex);
    current = entry->post_callbacks;
    
    while (current) {
        // 调用回调函数
        current->callback(context, current->user_data);
        current = current->next;
    }
    
    pthread_mutex_unlock(&entry->mutex);
}

/**
 * 加载插件
 */
int load_plugin(const char* plugin_path) {
    if (!plugin_path) return 0;
    
    pthread_mutex_lock(&g_framework_mutex);
    
    // 检查是否达到最大插件数量
    if (g_plugin_count >= sizeof(g_plugins) / sizeof(g_plugins[0])) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_ERROR, "加载插件失败: 已达到最大插件数量");
        return 0;
    }
    
    // 打开动态库
    void* handle = dlopen(plugin_path, RTLD_NOW | RTLD_LOCAL);
    if (!handle) {
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_ERROR, "加载插件失败: %s - %s", plugin_path, dlerror());
        return 0;
    }
    
    // 查找并调用初始化函数
    plugin_init_t init_func = dlsym(handle, "plugin_init");
    if (!init_func) {
        dlclose(handle);
        pthread_mutex_unlock(&g_framework_mutex);
        log_message(LOG_ERROR, "加载插件失败: %s - 未找到plugin_init函数", plugin_path);
        return 0;
    }
    
    // 保存插件句柄
    g_plugins[g_plugin_count++] = handle;
    
    pthread_mutex_unlock(&g_framework_mutex);
    
    // 调用初始化函数
    if (init_func() == 0) {
        log_message(LOG_ERROR, "插件初始化失败: %s", plugin_path);
        return 0;
    }
    
    log_message(LOG_INFO, "已加载插件: %s", plugin_path);
    return 1;
}

/**
 * 获取原始函数指针
 */
void* get_original_function(const char* name) {
    if (!name) return NULL;
    
    void* func = dlsym(RTLD_NEXT, name);
    if (!func) {
        log_message(LOG_WARN, "获取原始函数失败: %s - %s", name, dlerror());
    }
    
    return func;
}

/**
 * 记录日志消息
 */
void log_message(int level, const char* format, ...) {
    if (level > g_log_level) return;
    
    static const char* level_names[] = {
        "错误", "警告", "信息", "调试"
    };
    
    char timestamp[32];
    get_timestamp_str(timestamp, sizeof(timestamp));
    
    fprintf(stderr, "[%s] %s: ", timestamp, level_names[level]);
    
    va_list args;
    va_start(args, format);
    vfprintf(stderr, format, args);
    va_end(args);
    
    fprintf(stderr, "\n");
    fflush(stderr);
}

/**
 * 设置日志级别
 */
void set_log_level(int level) {
    if (level >= LOG_ERROR && level <= LOG_DEBUG) {
        g_log_level = level;
        log_message(LOG_INFO, "设置日志级别为: %d", level);
    } else {
        log_message(LOG_WARN, "无效的日志级别: %d", level);
    }
}

/**
 * 获取当前时间戳（毫秒）
 */
int64_t get_current_timestamp_ms(void) {
    return get_timestamp_ms();
}

/**
 * 获取当前线程ID
 */
uint32_t get_thread_id(void) {
    return (uint32_t)pthread_self();
}

/**
 * 获取当前进程ID
 */
uint32_t get_process_id(void) {
    return (uint32_t)getpid();
}

/**
 * 获取可执行文件路径
 */
int get_executable_path(char* buffer, size_t size) {
    if (!buffer || size == 0) return 0;
    
    ssize_t len = readlink("/proc/self/exe", buffer, size - 1);
    if (len > 0) {
        buffer[len] = '\0';
        return 1;
    }
    
    return 0;
}

/**
 * 设置上下文标志
 */
void set_context_flag(hook_context_t* context, uint32_t flag) {
    if (context) {
        context->flags |= flag;
    }
}

/**
 * 清除上下文标志
 */
void clear_context_flag(hook_context_t* context, uint32_t flag) {
    if (context) {
        context->flags &= ~flag;
    }
}

/**
 * 检查上下文标志
 */
int check_context_flag(hook_context_t* context, uint32_t flag) {
    if (!context) return 0;
    return (context->flags & flag) ? 1 : 0;
}

/**
 * 打印内存内容
 */
void dump_memory(const void* data, size_t size, const char* prefix) {
    if (!data || size == 0) return;
    
    const unsigned char* bytes = (const unsigned char*)data;
    char line[128];
    size_t offset = 0;
    
    for (size_t i = 0; i < size; i++) {
        if (i % 16 == 0) {
            if (i > 0) {
                fprintf(stderr, "%s%s\n", prefix ? prefix : "", line);
            }
            offset = snprintf(line, sizeof(line), "%04zx: ", i);
        }
        
        offset += snprintf(line + offset, sizeof(line) - offset, "%02x ", bytes[i]);
        
        if ((i + 1) % 16 == 0 || i == size - 1) {
            // 对齐空格
            for (int j = (i % 16) + 1; j < 16; j++) {
                offset += snprintf(line + offset, sizeof(line) - offset, "   ");
            }
            
            // 添加ASCII表示
            offset += snprintf(line + offset, sizeof(line) - offset, " | ");
            
            for (int j = i - (i % 16); j <= i; j++) {
                unsigned char ch = (j < size) ? bytes[j] : ' ';
                offset += snprintf(line + offset, sizeof(line) - offset, 
                                 "%c", (ch >= 32 && ch <= 126) ? ch : '.');
            }
        }
    }
}

/* ===== 自动初始化和清理 ===== */

/**
 * 自动初始化函数
 */
__attribute__((constructor))
static void auto_init(void) {
    init_hook_framework();
}

/**
 * 自动清理函数
 */
__attribute__((destructor))
static void auto_cleanup(void) {
    cleanup_hook_framework();
} 